package cn.kgc.tangcco.tcbd1011.booktype.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import cn.kgc.tangcco.tcbd1011.booktype.dao.BookTypeDao;
import cn.kgc.tangcco.tcbd1011.booktype.entity.BookType;
import cn.kgc.tangcco.tcbd1011.util.JDBCUtil;

public class BookTypeDaoImpl implements BookTypeDao{
	private QueryRunner queryRunner=new QueryRunner(JDBCUtil.getDataSource());
	
	public int executeUpdate(String sql,Object...obj) {
		try {
			return this.queryRunner.update(sql, obj);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}
	@Override
	public int addBookType(BookType bookType) {
		return this.executeUpdate("insert into booktype values(default,?)", bookType.getTypename());
		
	}

	@Override
	public int updateBookType(BookType bookType) {
		return this.executeUpdate("update booktype set typename=? where typeid=?", bookType.getTypename(),bookType.getTypeid());
	}

	@Override
	public int deleteBookType(int pk) {
		try {
			return this.queryRunner.update("delete from booktype where typeid=?", pk);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
		
	}

	@Override
	public BookType detailBookTypeById(int pk) {
		try {
			return this.queryRunner.query("select * from booktype where typeid=?", new BeanHandler<>(BookType.class), pk);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public List<BookType> queryAllBook() {
		try {
			return this.queryRunner.query("select * from booktype order by typeid desc", new BeanListHandler<>(BookType.class));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	@Override
	public List<BookType> queryTypeToBooks() {
		try {
			return this.queryRunner.query("select * from booktype order by typeid desc", new BeanListHandler<>(BookType.class));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

}
